package com.grp6.game.ui.platform.swing;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;

import com.grp6.game.ui.platform.IActionListener;
import com.grp6.game.ui.platform.ICell;
import com.grp6.game.ui.platform.swing.SwingUIFactory.BaseFrame;

public class SwingCell extends JButton implements ICell,ActionListener {
	private static final long serialVersionUID = 1L;
	private static HashMap<String,Image> imageCache = new HashMap<String, Image>();
	private ArrayList<IActionListener> listeners = new ArrayList<IActionListener>();
	
	private Image overlayImage;
	ImageIcon cellIcon;
	private BaseFrame baseFrame;
	private synchronized Image getImage(String fileName){
		Image image = imageCache.get(fileName);
		if (image==null){
			InputStream resource = ICell.class.getClassLoader().getResourceAsStream(fileName);
			try {
				image = ImageIO.read(resource);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
			imageCache.put(fileName, image);
		}
		return image;
	}
	
	public SwingCell(BaseFrame baseFrame,int x,int y) {
		this.baseFrame = baseFrame;
		GridBagConstraints constraints = new GridBagConstraints();
		constraints.gridx=x;
		constraints.gridy=y;
		baseFrame.add(this,constraints);
		this.addActionListener(this);
	}

	@Override
	public void setTile(String style){
		cellIcon = new ImageIcon(getImage(style+".png"));
		this.setIcon(cellIcon);
		Dimension dim = new Dimension(cellIcon.getIconWidth(),cellIcon.getIconHeight());
		this.setMaximumSize(dim);
		this.setMinimumSize(dim);
		this.setPreferredSize(dim);
		baseFrame.pack();
		this.repaint();
	}

	@Override
	public synchronized void setSymbol(String symbol) {
		if (symbol==null)
			overlayImage = null;
		else
			overlayImage = getImage(symbol+".png");
		
		this.repaint();
	}

	@Override
	public void setHighlight(boolean on) {
		// FIXME not implemented
	}

	@Override
	public void addActionListerner(IActionListener listener) {
		listeners.add(listener);
	}
	
	public synchronized void paint(Graphics g){
		super.paint(g);
		if (overlayImage!=null)
			g.drawImage(overlayImage, 0, 0, cellIcon.getIconWidth(), cellIcon.getIconHeight(), null);
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		for(IActionListener l:listeners)
			l.actionPerformed("click");
	}

}
